<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">











<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "9c84d93b"
    });
  daovoice('update');
  </script>












<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=6.1.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=6.1.0">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=6.1.0" color="#222">







<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
</script>


<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Muse',
    version: '6.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="引言线程是进程中执行的最小运算单位，也是执行处理机调度的基本单位。一个线程只属于一个进程，一个进程包含多个线程。  多线程：指的是这个程序（一个进程）运行时产生了多个线程。 并行与并发： 并行（Parallel）：多个cpu实例或者多台机器同时执行一段处理逻辑，是真正的同时。 并发（Concurrent）：通过CPU调度算法，让用户看上去同时执行，实际上从CPU操作层面不是真正的同时。并发往往在场">
<meta name="keywords" content="java,多线程">
<meta property="og:type" content="article">
<meta property="og:title" content="Java多线程">
<meta property="og:url" content="http://zhangsnke.gitee.io/2019/01/15/Java多线程/index.html">
<meta property="og:site_name" content="Zhangsnke&#39;s Blog">
<meta property="og:description" content="引言线程是进程中执行的最小运算单位，也是执行处理机调度的基本单位。一个线程只属于一个进程，一个进程包含多个线程。  多线程：指的是这个程序（一个进程）运行时产生了多个线程。 并行与并发： 并行（Parallel）：多个cpu实例或者多台机器同时执行一段处理逻辑，是真正的同时。 并发（Concurrent）：通过CPU调度算法，让用户看上去同时执行，实际上从CPU操作层面不是真正的同时。并发往往在场">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://wx2.sinaimg.cn/mw690/0060lm7Tly1fz77tszompj30ds0dzq5c.jpg">
<meta property="og:image" content="http://wx2.sinaimg.cn/mw690/0060lm7Tly1fz7874ii4gj31a00f8adp.jpg">
<meta property="og:image" content="http://wx4.sinaimg.cn/mw690/0060lm7Tly1fz789yosq6j30gt0bnmz6.jpg">
<meta property="og:image" content="http://wx4.sinaimg.cn/mw690/0060lm7Tly1fz78tkyvv5j30ev0a2aal.jpg">
<meta property="og:image" content="http://wx3.sinaimg.cn/mw690/0060lm7Tly1fz79xky7vcj30fs0gggma.jpg">
<meta property="og:image" content="http://wx1.sinaimg.cn/mw690/0060lm7Tly1fz7dhnxem8j30af06d0tv.jpg">
<meta property="og:image" content="http://wx1.sinaimg.cn/mw690/0060lm7Tly1fz7dud7gzvj30eb037a9v.jpg">
<meta property="og:image" content="http://wx3.sinaimg.cn/mw690/0060lm7Tly1fz7e6jkngnj30ju08fwej.jpg">
<meta property="og:updated_time" content="2019-01-15T09:29:04.938Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java多线程">
<meta name="twitter:description" content="引言线程是进程中执行的最小运算单位，也是执行处理机调度的基本单位。一个线程只属于一个进程，一个进程包含多个线程。  多线程：指的是这个程序（一个进程）运行时产生了多个线程。 并行与并发： 并行（Parallel）：多个cpu实例或者多台机器同时执行一段处理逻辑，是真正的同时。 并发（Concurrent）：通过CPU调度算法，让用户看上去同时执行，实际上从CPU操作层面不是真正的同时。并发往往在场">
<meta name="twitter:image" content="http://wx2.sinaimg.cn/mw690/0060lm7Tly1fz77tszompj30ds0dzq5c.jpg">






  <link rel="canonical" href="http://zhangsnke.gitee.io/2019/01/15/Java多线程/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Java多线程 | Zhangsnke's Blog</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
<a href="https://github.com/zxk318www"><img style="position: absolute; top: 0; left: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_left_gray_6d6d6d.png" alt="Fork me on GitHub"></a>
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Zhangsnke's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
          
  
  <li class="menu-item menu-item-home menu-item-active">
    <a href="/blog/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
</li>

      
        
        
          
  
  <li class="menu-item menu-item-about">
    <a href="/blog/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
</li>

      
        
        
          
  
  <li class="menu-item menu-item-tags">
    <a href="/blog/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
</li>

      
        
        
          
  
  <li class="menu-item menu-item-categories">
    <a href="/blog/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
</li>

      
        
        
          
  
  <li class="menu-item menu-item-archives">
    <a href="/blog/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
</li>

      

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://zhangsnke.gitee.io/blog/2019/01/15/Java多线程/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Zhangsnke">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="http://wx1.sinaimg.cn/mw690/0060lm7Tly1fz2r82s43bj30u20u0ad9.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Zhangsnke's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Java多线程</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-01-15T17:28:39+08:00">2019-01-15</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/blog/categories/java基础知识/" itemprop="url" rel="index"><span itemprop="name">java基础知识</span></a></span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blog/2019/01/15/Java多线程/#comments" itemprop="discussionUrl">
                  <span class="post-meta-item-text">评论数：</span> <span class="post-comments-count valine-comment-count" data-xid="/blog/2019/01/15/Java多线程/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="引言"><a href="#引言" class="headerlink" title="引言"></a>引言</h1><p>线程是进程中执行的最小运算单位，也是执行处理机调度的基本单位。一个线程只属于一个进程，一个进程包含多个线程。</p>
<ul>
<li>多线程：指的是这个程序（一个进程）运行时产生了多个线程。</li>
<li>并行与并发：<ul>
<li>并行（Parallel）：多个cpu实例或者多台机器同时执行一段处理逻辑，是真正的同时。</li>
<li>并发（Concurrent）：通过CPU调度算法，让用户看上去同时执行，实际上从CPU操作层面不是真正的同时。并发往往在场景中有公共的资源，那么针对这个公共资源往往产生瓶颈，一般会用TPS或者QPS来反应这个系统的处理能力。<br><img src="http://wx2.sinaimg.cn/mw690/0060lm7Tly1fz77tszompj30ds0dzq5c.jpg" alt="图1|center"></li>
</ul>
</li>
<li>线程安全与同步：<ul>
<li>线程安全：经常用来描述一段代码。指在并发的情景下，该代码经过多线程使用，线程的调度顺序不影响任何结果。</li>
<li>同步：Java中的同步指的是通过人为的控制和调度，保证共享资源的多线程访问成为线程安全，来保证记过的准确。线程安全优先级高于性能。</li>
</ul>
</li>
</ul>
<hr>
<h1 id="线程状态"><a href="#线程状态" class="headerlink" title="线程状态"></a>线程状态</h1><p><strong>线程状态</strong><br><img src="http://wx2.sinaimg.cn/mw690/0060lm7Tly1fz7874ii4gj31a00f8adp.jpg" alt="图2|center"></p>
<p><strong>线程转换</strong><br><img src="http://wx4.sinaimg.cn/mw690/0060lm7Tly1fz789yosq6j30gt0bnmz6.jpg" alt="图3|center"></p>
<p><strong>blocked状态</strong><br>线程在 <strong>Running</strong> 的过程中可能会遇到阻塞（Blocked）：</p>
<ol>
<li>调用 join() 和 sleep() 方法，sleep() 方法时间结束或被打断，join() 终端，I/O 完成都会回到 Runnable 状态，等待JVM 调度。</li>
<li>调用 wait()，使该线程处于等待池（wait blocked pool），直到 notify()/notifyAll()，线程被唤醒被放到锁定池（lock blocked pool），释放同步锁使线程回到可运行状态（Runable）。</li>
<li>对 Running 状态的线程加同步锁（Synchronized）使其进入锁定池（lock blocked pool），同步锁释放可以进入可运行状态（Runnable）</li>
</ol>
<p>此外，在 Runable 状态的线程是处于被调度的线程，此时的调度顺序是不一定的。Thread类中的 yield() 方法可以让一个running 状态的线程转入 runnable。</p>
<hr>
<h1 id="每个对象都有的方法（机制）"><a href="#每个对象都有的方法（机制）" class="headerlink" title="每个对象都有的方法（机制）"></a>每个对象都有的方法（机制）</h1><p>Synchronized、wait、notify 是任何对象都具有的同步工具。<br><img src="http://wx4.sinaimg.cn/mw690/0060lm7Tly1fz78tkyvv5j30ev0a2aal.jpg" alt="图4|center"></p>
<p><strong>monitor</strong><br><a href="http://www.php.cn/java-article-410323.html" target="_blank" rel="noopener">点击查看详情</a><br><em>是应用于同步问题的人工线程调度工具。讲其本质，首先就要明确 monitor 的概念，Java 中的每个对象都有一个监视器，来监测并发代码的重入。在非多线程编码时，该监视器不发挥作用，反之如果在 synchronized 范围内，监视器发挥作用。</em></p>
<p>wait()/notify() 必须存在于 synchronized 块中。并且，这三个关键字针对的是同一个监视器（某对象的监视器）。这意味着 wait 之后，其他的线程可以进入同步块执行。</p>
<p>当某代码并不持有监视器的使用权时（如图中5的状态，即脱离同步块）去 wait 或 notify ，会抛出 java.lang.IllegalMonitorStateException。也包括在 synchronized 块中去调用另一个对象的 wait /notify ，因为不同对象的监视器不同，也会抛出此异常。</p>
<p>用法：</p>
<ul>
<li>synchronized 单独使用：<ul>
<li>代码块：如下，在多线程环境下，synchronized 块中的方法获取了 lock 实例的 monitor，如果实例相同，那么只有一个线程能执行该代码块内容<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Thread1</span> <span class="keyword">implements</span> <span class="title">Runnable</span> </span>&#123;</span><br><span class="line"> Object lock;</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span></span>&#123;</span><br><span class="line">  <span class="keyword">synchronized</span>(lock)&#123;</span><br><span class="line">	  ..<span class="keyword">do</span> something</span><br><span class="line">  &#125;</span><br><span class="line">&#125; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ul>
<ul>
<li>直接用于方法：相当于上面代码中用 lock 来锁定的效果，实际获取的是 Thread1 类的 monitor 。更进一步，如果直接修饰的是 static 方法，则锁定该类所有实例。<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Thread1</span> <span class="keyword">implements</span> <span class="title">Runnable</span></span>&#123;</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span></span>&#123;</span><br><span class="line">  ..<span class="keyword">do</span> something</span><br><span class="line"> &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<ul>
<li>synchronized，wait，notify 结合：景点场景生产者和消费者问题<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">* 生产者产出产品</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">produce</span><span class="params">()</span></span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (<span class="keyword">this</span>.product &gt;= MAX_PRODUCT)&#123;</span><br><span class="line">		<span class="keyword">try</span>&#123;</span><br><span class="line">		&#125;<span class="keyword">catch</span>(InterruptedException e)&#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">this</span>.product++;</span><br><span class="line">	System.out.println(<span class="string">"生产者生产第"</span>+ <span class="keyword">this</span>.product + <span class="string">"个产品"</span>);</span><br><span class="line">	notifyAll(); <span class="comment">//通知等待区的消费者可以取出产品</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">*	消费者消费产品</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">consume</span><span class="params">()</span></span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (<span class="keyword">this</span>.product &lt;= MIN_PRODUCT)&#123;</span><br><span class="line">		<span class="keyword">try</span>&#123;</span><br><span class="line">		&#125;<span class="keyword">catch</span>(InterruptedException e)&#123;</span><br><span class="line">			e.printStackTrace();</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">return</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	System.out.println(<span class="string">"消费者取走了第"</span>+ <span class="keyword">this</span>.product +<span class="string">"个产品"</span>)；</span><br><span class="line">	<span class="keyword">this</span>.product--;</span><br><span class="line">	notifyAll(); <span class="comment">//通知等待区的生产者可以生产产品了</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p><strong>volatile</strong><br><em>多线程的内存模型：main memory（主存）、working memory（线程栈），在处理数据时，线程会把值从主存 load 到本地栈，完成操作后再 save 回去（volatile关键字的作用：每次针对该变量的操作都会激发一次  load and save）</em><br><img src="http://wx3.sinaimg.cn/mw690/0060lm7Tly1fz79xky7vcj30fs0gggma.jpg" alt="图5|center"></p>
<p>针对多线程使用的变量，如果不是 volatile 或者 final 修饰的，很有可能产生不可预知的结果（另一个线程修改了这个值，但是之后再某线程看到的是修改之前的值）。其实道理上讲同一个属性本身只有一个副本。但是多线程会缓存值，本质上，volatile 就是不去缓存，直接取值。在线程安全的情况下加 volatile 会牺牲性能。</p>
<hr>
<h1 id="基本线程类"><a href="#基本线程类" class="headerlink" title="基本线程类"></a>基本线程类</h1><p><strong>基本线程类指的是 Thread 类，Runnable 接口，Callable 接口</strong><br><em>Thread 类实现了 Runnable 接口，启动一个线程的方法</em><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">MyThread my = <span class="keyword">new</span> MyThread();</span><br><span class="line">my.start();</span><br></pre></td></tr></table></figure></p>
<p><strong>Thread类相关方法</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">   <span class="comment">//当线程可以转让CPU控制权，让别的就绪态的线程运行（切换）</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> Thread.yield()</span><br><span class="line"><span class="comment">//暂停一段时间</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> Thread.sleep()</span><br><span class="line"><span class="comment">//在一个线程中调用other.join()，将等待other执行完后才继续本线程</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">join</span><span class="params">()</span></span></span><br><span class="line"><span class="function"><span class="comment">//后两个函数皆可以被打断</span></span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">interrupte</span><span class="params">()</span></span></span><br></pre></td></tr></table></figure></p>
<p><strong>关于中断</strong><br>它并不像 stop 方法那样会中断一个正在运行的线程。线程会不时地检测中断标识位，以判断线程是否应该被中断（中断标示值是否为 true ）。中断只会影响到 wait 状态、sleep 状态和 join 状态。被打断的线程会抛出 InterruptedException。<br>Thread.interrupted() 检查当前线程是否发生中断，返回boolean<br>synchronized 在获取锁的过程中是不能被中断的。</p>
<p>中断是一个状态，interrupt() 方法只是将这个状态置为 true 而已。所以说正常运行的程序不去检查状态，就不会终止，而 wait 等阻塞方法会去检查并抛出异常。如果在正常运行的程序中添加 while(!Thread.interruped())，则同样可以在中断后离开代码体。</p>
<p><strong>Thread类最佳实践</strong><br><em>写的时候最好要设置线程名称 Thread.name ，并设置线程组 ThreadGroup，目的是方便管理，如果出现问题，打印线程栈（jstack-pid）一眼就能看出是哪个线程出现问题，这个线程的主要作用是什么</em></p>
<p><strong>如何获取线程中的异常</strong><br><em><font color="red">线程是独立执行的代码片段，线程的问题应该由线程自己来解决，而不要委托到外部。</font></em></p>
<p>线程方法的异常应该在线程代码边界之内（run方法内）进行try catch并处理掉，不能捕获从线程中逃逸的异常。</p>
<p><em>JDK1.5之后有了一个 Thread.UncaughtExceptionHandler 新接口，它允许我们再每一个 Thread 对象上添加一个异常处理器。Thread.UncaughtExceptionHandler.uncaughtException() 方法会在线程因未捕获的异常而面临死亡时被调用。</em><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyUncheckedExceptionHandler</span> <span class="keyword">implements</span> <span class="title">UncaughtExceptionHandler</span></span>&#123;</span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">uncaughtException</span><span class="params">(Thread t , Throwable e)</span></span>&#123;</span><br><span class="line">	 	System,out.println(<span class="string">"捕获异常处理方法"</span>+ e);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>三种方式使用该线程异常捕获器：</p>
<ol>
<li><p>在创建线程的时候进行设置</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Thread t = <span class="keyword">new</span> Thread(<span class="keyword">new</span> ExceptionThread());</span><br><span class="line">t.setUncaughtExceptionHandler(<span class="keyword">new</span> MyUncheckedExceptionHandler());</span><br><span class="line">t.start();</span><br></pre></td></tr></table></figure>
</li>
<li><p>使用 Executors 创建线程时，还可以在 ThreadFactory 中设置</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">ExecutorService exec = Executors.newCachedThreadPool(<span class="keyword">new</span> ThreadFactory()&#123;</span><br><span class="line">	<span class="meta">@Override</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> Thread <span class="title">newThread</span><span class="params">(Runnable r)</span></span>&#123;</span><br><span class="line">		Thread thread = <span class="keyword">new</span> Thread(r);</span><br><span class="line">		thread.setUncaughtExceptionHandler(<span class="keyword">new</span> MyUncheckedExceptionHandler());</span><br><span class="line">		<span class="keyword">return</span> thread;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;);</span><br><span class="line">exec.excute(<span class="keyword">new</span> ExceptionThread());</span><br></pre></td></tr></table></figure>
</li>
<li><p>如果只需要一个线程异常处理器处理线程的异常，可以设置一个默认的线程异常捕获器；如果没有指定线程的异常捕获器，而且线程组也没有设置（线程组不用考虑，因为这是一个不成功的尝试），那么就会使用默认的线程异常捕获器</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//设置默认的线程异常捕获器</span></span><br><span class="line">Thread.setDefaultUncaughtExceptionHandler(<span class="keyword">new</span> MyUncheckedExceptionHandler());</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p><strong>Runnable</strong><br>与Thread类似</p>
<p><strong>Callable</strong><br><em>future 模式：并发模式的一种，可以有两种形式，即无阻塞和阻塞，分别是 isDone 和 get,其中 Future 对象用来存放 该线程的返回值以及状态。</em><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">ExecutorService e = Executors.newFixedThreadPool(<span class="number">3</span>)</span><br><span class="line"><span class="comment">//submit 方法有多重参数版本，以及支持callable 也能够支持 runnable 接口类型</span></span><br><span class="line">Future future = e.submit(<span class="keyword">new</span> myCallable());</span><br><span class="line">future.isDone(); <span class="comment">//return boolean 无阻塞</span></span><br><span class="line">future.get();  <span class="comment">//return 返回值，阻塞直到该线程运行结束</span></span><br></pre></td></tr></table></figure></p>
<hr>
<h1 id="高级多线程控制类"><a href="#高级多线程控制类" class="headerlink" title="高级多线程控制类"></a>高级多线程控制类</h1><p><em>Java1.5提供了一个非常高效实用的多线程包：java.util.concurrent，提供了大量高级工具，可以帮助开发者编写高效、易维护、结构清晰的Java多线程程序。</em></p>
<p><strong>1.ThreadLocal类</strong></p>
<p><font color="red">用处</font>：保存线程的独立变量。对一个线程类（继承自 Thread ）<br>当使用 ThreadLocal 维护变量时，ThreadLocal 为每个使用该变量的线程提供独立的变量副本，所以每一个线程都可以独立地改变自己的副本，而不会影响到其他线程所对应的副本。常用于用户登录控制，如记录 session 信息。</p>
<p><font color="blue">实现</font>：每个 Thread 都持有一个 ThreadLocalMap 类型的变量（该类是一个轻量级的 Map ，功能与 map 一样，区别是桶里放的是 entry 而不是 entry 的链表。功能还会死一个 map）以本身为 key，以目标为 value。<br>主要方法式 get() 和 set(T a)，set 之后在 map 里维护一个 threadLocal -&gt;a ,get时将 a 返回。ThreadLocal 是一个特殊的容器。</p>
<p><strong>2.原子类（AtomicInteger、AutoBoolean…）</strong><br>如果使用 atomic  wrapper class 如 atomicInteger，或者使用自己保证原子的操作，等同于 synchronized<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//返回值为boolean</span></span><br><span class="line">AtomicInteger.compareAndSet(<span class="keyword">int</span> expect,<span class="keyword">int</span> update)</span><br></pre></td></tr></table></figure></p>
<p>该方法可用于实现乐观锁<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (b.value.compareAndSet(old,value))&#123;</span><br><span class="line">	<span class="keyword">return</span>;</span><br><span class="line">&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">	<span class="comment">//try again</span></span><br><span class="line">	<span class="comment">// if that fails,rollback and log</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>AtomicReference</strong><br>对于 AtomicReference 来讲，也许对象会出现 属性丢失的情况，即 oldObject == current，但是 oldObject.getPropertyA != current.getPropertyA。<br>这时候 AtomicStampedReference派上用处，加上了版本号。</p>
<p><strong>3.Lock类</strong><br>locak 在 java.util.concurrent 包内。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ReentrantLock</span><br><span class="line">ReentrantReadWriteLock.ReadLock</span><br><span class="line">ReentrantReadWriteLock.WriteLock</span><br></pre></td></tr></table></figure></p>
<p>主要目的是和 synchronized 一样，两者都是为了解决同步问题，处理资源争端而产生的技术。<br>区别：<br>lock 更灵活，可以自由定义多把锁的枷锁解锁顺序（synchronized 要按照<font color="red">先加的后解锁顺序</font>）提供多种枷锁方案，lock 阻塞式，trylock 无阻塞式，lockInterruptily 可打断式，还有 trylock 带超时版本。本质上和监视器锁（即  synchronized是一样的）和Condition类的结合，性能更高。<br><img src="http://wx1.sinaimg.cn/mw690/0060lm7Tly1fz7dhnxem8j30af06d0tv.jpg" alt="图6|center"></p>
<p><strong>ReentrantLock</strong><br>可重入的意义在于持有锁的线程可以继续持有，并且要释放对等的次数后才是真正释放该锁。<br>使用方法：</p>
<ol>
<li><p>先 new 一个实例</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> ReentrantLock r = <span class="keyword">new</span> ReentrantLock();</span><br></pre></td></tr></table></figure>
</li>
<li><p>枷锁</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">r.lock()或r.lockInterruptibly();</span><br></pre></td></tr></table></figure>
</li>
<li><p>释放锁（必须做，要放在finally里面，防止异常跳出正常流程）</p>
 <figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">r.unlock();</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p><strong>ReentrantReadWriteLock</strong><br>可重入读写锁（读写锁的实现）<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ReentrantReadWriteLock lock = <span class="keyword">new</span> ReentrantReadWriteLock();</span><br><span class="line">ReadLock r = lock.readLock();</span><br><span class="line">WriteLock w = lock.writeLock();</span><br></pre></td></tr></table></figure></p>
<p>两者都有 lock ，unlock 方法。写写，写读互斥；读读不互斥，实现并发读的高效线程安全代码。</p>
<p><strong>4.容器类</strong><br>比较常用的：BlockingQueue 和 ConcurrentHashMap</p>
<p><strong>BlockingQueue</strong><br><strong>阻塞队列</strong>。改类是 java.util.concurrent 包下重要类，通过对 Queue 的学习可以得知，这个 queue 是单向队列，可以在队列头添加元素和在队尾删除或取出元素。类似一个 管道 ，特别适合用于先进先出策略的一些应用场景。普通的 queue 接口主要实现由 PriorityQueue（优先队列）<br><img src="http://wx1.sinaimg.cn/mw690/0060lm7Tly1fz7dud7gzvj30eb037a9v.jpg" alt="图7|center"><br>除了传统的 queue 功能（表格左边的两列）之外，还提供了阻塞接口 put 和 take，带超时功能的阻塞接口 offer 和 poll。put 会在队列满的时候阻塞，知道有空间时被唤醒；take 在队列空的时候阻塞，知道有东西拿的时候才被唤醒。用于生产者-消费者模型尤其好用。<br>常见的阻塞队列有：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">ArrayListBlockingQueue</span><br><span class="line">LinkedListBlockingQueue</span><br><span class="line">DelayQueue</span><br><span class="line">SynchronousQueue</span><br></pre></td></tr></table></figure></p>
<p><strong>ConcurrentHashMap</strong><br>高效的线程安全HashMap。</p>
<p><strong>5.管理类</strong><br>管理类用于管理线程。本身不是多线程的，但是提供了一些机制来利用上述的工具做一些封装。<br>ThreadPoolExecutor 和 JMX 框架下的系统级管理类 ThreadMXBean</p>
<p><strong>ThreadPoolExecutor</strong><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//可变大小的线程池，按照任务数来分配线程</span></span><br><span class="line">ExecutorService e = Executors.newCachedThrreadPool();</span><br><span class="line"><span class="comment">//单线程池，相当于 FixedThread(1)</span></span><br><span class="line">ExecutorService e = Executors.newSingleThreadExecutor();</span><br><span class="line"><span class="comment">//固定大小的线程池</span></span><br><span class="line">ExecutorService e = Executors.newFixedThreadPool(<span class="number">3</span>);</span><br><span class="line">e.execute(<span class="keyword">new</span> MyRunnableImpl());</span><br></pre></td></tr></table></figure></p>
<p>该类内部是通过 ThreaPoolExecutor 实现的，本质上都是 ThreadPoolExecutor 类的各种实现版本<br><img src="http://wx3.sinaimg.cn/mw690/0060lm7Tly1fz7e6jkngnj30ju08fwej.jpg" alt=""><br>翻译：<br>corePoolSize：池内线程初始值和最小值，就算是空闲状态，也会保持该数量线程。<br>maximumPoolSize：线程最大值，线程的增长始终不会超过该值<br>keepAliveTime：当线程池数高于 corePoolSize 时，经过多少时间多余的空闲池才会被回收，回收前处于 wait 状态 unit：时间单位，可以使用 TimeUnit 实例，如 TimeUnit.MILLISECONDS<br>workQueue：等待入任务（Runnable）的等待场所，该参数主要影响调度策略，如公平与否，是否会产生饿死（starving）<br>threadFactory：线程工厂类，有默认的实现，如果有自定义的需要则需要自己实现 ThreadFactory 接口并作为参数传入。</p>
<hr>

      
    </div>

    

    
    
    

<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
  
</div>

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="http://wx4.sinaimg.cn/mw690/0060lm7Tly1fq7f9mgftqj30yf11x793.jpg" alt="Zhangsnke 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="http://wx2.sinaimg.cn/mw690/0060lm7Tly1fq7f9yogljj30ox0qi76z.jpg" alt="Zhangsnke 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/java/" rel="tag"><i class="fa fa-tag"></i> java</a>
          
            <a href="/blog/tags/多线程/" rel="tag"><i class="fa fa-tag"></i> 多线程</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/01/11/集合类/" rel="next" title="必知必会Java面试题">
                <i class="fa fa-chevron-left"></i> 必知必会Java面试题
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/01/17/Linux使用注意事项/" rel="prev" title="Linux使用注意事项">
                Linux使用注意事项 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="uyan_frame"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="http://wx1.sinaimg.cn/mw690/0060lm7Tly1fz2r82s43bj30u20u0ad9.jpg"
                alt="Zhangsnke" />
            
              <p class="site-author-name" itemprop="name">Zhangsnke</p>
              <p class="site-description motion-element" itemprop="description">java jsp</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/blog/archives/">
                
                    <span class="site-state-item-count">11</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/blog/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">4</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/blog/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">8</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/zxk318www" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:1137824821@qq.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/u/3487862312" target="_blank" title="Weibo"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#引言"><span class="nav-number">1.</span> <span class="nav-text">引言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#线程状态"><span class="nav-number">2.</span> <span class="nav-text">线程状态</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#每个对象都有的方法（机制）"><span class="nav-number">3.</span> <span class="nav-text">每个对象都有的方法（机制）</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#基本线程类"><span class="nav-number">4.</span> <span class="nav-text">基本线程类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#高级多线程控制类"><span class="nav-number">5.</span> <span class="nav-text">高级多线程控制类</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Zhangsnke</span>

  

  
</div>




<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>
  <!-- <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Muse</a> v6.1.0</div>
-->





<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共28.7k字</span>
</div>
        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=6.1.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=6.1.0"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=6.1.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=6.1.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=6.1.0"></script>



  



	





  
    

    
      <!-- UY BEGIN -->
      <script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=2161053"></script>
      <!-- UY END -->
    
  





  








  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  
  
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(function (item) {
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'V4OQTBV0QUJvAOnALRUDikMp-gzGzoHsz',
        appKey: 'Ygfy3JqhxL8KArimEFAGB3QQ',
        placeholder: 'ヾﾉ≧∀≦)o来啊，快活啊!',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  


<script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
</body>
</html>

